package com.liyueheng.util

import java.io.{FileInputStream, FileNotFoundException, IOException}
import java.util.Properties

object ConfigLoader {
  private val properties: Properties = {
    val prop = new Properties()
    var inputStream: Option[java.io.InputStream] = None

    try {
      // 优先从外部配置文件加载
      val externalPath = Option(System.getProperty("config.file"))
      inputStream = externalPath.map(new FileInputStream(_))

      // 如果外部配置不存在，尝试从classpath加载
      if (inputStream.isEmpty) {
        inputStream = Option(
          getClass.getClassLoader.getResourceAsStream("application.properties")
        )
      }

      inputStream match {
        case Some(stream) =>
          prop.load(stream)
          stream.close()
        case None =>
          throw new FileNotFoundException(
            "Configuration file not found in classpath and no external config specified"
          )
      }
    } catch {
      case e: FileNotFoundException =>
        throw new RuntimeException("Configuration file not found", e)
      case e: IOException =>
        throw new RuntimeException("Error reading configuration file", e)
      case e: Exception =>
        throw new RuntimeException("Unexpected error during configuration loading", e)
    } finally {
      inputStream.foreach(_.close())
    }

    prop
  }

  // 安全的获取配置方法（推荐直接使用这些方法）
  def getString(key: String): String = {
    Option(properties.getProperty(key)).getOrElse(
      throw new NoSuchElementException(s"Configuration key '$key' not found")
    )
  }

  def getInt(key: String): Int = {
    try {
      getString(key).toInt
    } catch {
      case _: NumberFormatException =>
        throw new IllegalArgumentException(s"Value for key '$key' is not a valid integer")
    }
  }

  def getBoolean(key: String): Boolean = {
    getString(key).toLowerCase match {
      case "true" => true
      case "false" => false
      case other =>
        throw new IllegalArgumentException(s"Value '$other' for key '$key' is not a valid boolean")
    }
  }
}